<template>
  <!-- <difftest></difftest> -->
  <!-- <p>{{ this.data }}</p> -->
  <!-- <p>{{ this.options }}</p> -->
  <!-- <p>{{ this.diffsList }}</p> -->
  <!-- <p>{{ this.flattenedTree }}</p> -->
  <div v-loading="attr.loading">
    <el-row>
      <el-col align="bottom" justify="center" :span="23" :offset="1">
        <h2>配置文件比对</h2>
      </el-col>
    </el-row>

    <el-form v-for="(item, index) in data" label-position="left" label-width="auto">
      <el-row>

        <!-- 源分支或tag -->
        <el-col :span="10" :offset="1">
          <el-form-item label="Source">
            <!-- <el-config-provider :value-on-clear="null" :empty-values="[undefined, null]"> -->
            <el-cascader v-model="data[index].src"
              @change="fetchTree(data[index].src[0], data[index].src[2], 'src', index);"
              placeholder="Source Branch or Tag" :props="props" :options="options" filterable />
            <el-cascader v-model="data[index].srcPath" placeholder="" :props="propsPath"
              :options="this.flattenedTree['src' + index]" filterable />
            <!-- </el-config-provider> -->
          </el-form-item>
        </el-col>

        <!-- 目标分支或tag -->
        <el-col :span="10">
          <el-form-item label="Target">
            <el-cascader v-model="data[index].dest"
              @change="fetchTree(data[index].dest[0], data[index].dest[2], 'dest', index)"
              placeholder="Target Branch or Tag" :options="options" :props="props" filterable />
            <el-cascader v-model="data[index].destPath" placeholder="" :props="propsPath"
              :options="this.flattenedTree['dest' + index]" filterable />
          </el-form-item>
        </el-col>

        <!-- 删除 button -->
        <el-col :span="2">
          <el-form-item>
            <el-button v-if="data.length >= 2" @click="removeSetting(item, index)">删除</el-button>
          </el-form-item>
        </el-col>


        <!-- <el-col :span="10"></el-col> -->

      </el-row>
    </el-form>

    <el-row>

      <el-col :span="2" :offset="1">
        <el-button @click="addSetting()">新增对比</el-button>
      </el-col>

      <el-col :span="1" :offset="1">
        <el-button @click="fileDiff(data)">提交</el-button>
      </el-col>

    </el-row>

    <!-- 占位行 -->
    <el-row>
      <el-col style="min-height: 40px;"></el-col>
    </el-row>


    <!-- <el-row>
    <el-col :span="22" :offset="1"> -->
    <!-- 循环渲染子组件 -->
    <!-- <div>
        <DiffComponent v-for="(diff, index) in diffsList" :key="index" :diffs="diff" />
      </div>
    </el-col>
  </el-row> -->


    <!-- <div>
    <input v-model="projectId" placeholder="Project ID" />
    <input v-model="ref" placeholder="Branch/Tag" />
    <button @click="fetchTree">Fetch Tree</button>
    <select v-model="selectedPath" @change="handleSelectChange">
      <option v-for="item in flattenedTree" :key="item.id" :value="item.path">
        {{ item.path }}
      </option>
    </select>
    <p>Selected Path: {{ selectedPath }}</p>
  </div> -->

  </div>

  <!-- 进度条 -->
  <el-row >
    <el-col :span="22" :offset="1">
      <el-progress v-show="attr.percentage !== 100" :percentage="attr.percentage" />
    </el-col>
  </el-row>


  <el-row>
    <!-- 循环渲染子组件 -->
    <el-col :span="22" :offset="1">
       <!-- loading 遮罩 -->
      <div v-loading="attr.diffLoading">
        <div v-html="prettyHtml" />
      </div>
    </el-col>
  </el-row>


</template>

<script>
import DiffComponent from './DiffComponent.vue';
// import difftest from './fileDiff_test.vue';
import api from '../../api'
import * as Diff2Html from 'diff2html';
// import { ElLoading } from 'element-plus'

export default {
  name: 'ParentComponent',
  computed: {
    prettyHtml() {
      return Diff2Html.html(this.diffs, {
        drawFileList: true,
        matching: 'none',
        outputFormat: 'side-by-side',
        renderNothingWhenEmpty: false, // 内容相同没有改变不输出变化
        fileContentToggle: true, // 启用文件内容折叠功能
        highlight: true, // 启用代码高亮
        synchronisedScroll: true, // 启用同步滚动
      });
    },
  },
  components: {
    DiffComponent,
    // difftest
  },
  data() {
    return {
      // num: null,
      diffs: "",
      attr: {
        // 选择框加载框
        loading: true,
        // 等待后端比对加载框
        diffLoading: false,
        percentage: null,
      },
      diffsList: [
        '--- file1.txt\n+++ file2.txt\n@@ -1,4 +1,4 @@\n 111\n\n-22\n\n-333\n\n-aaa\\n\n+222\n\n+3334\n\n+aaa',
      ],
      // 存放项目名称和分支、tag 名称
      options: [],
      // 源 tag 和目标 tag 选中后存的数据
      data: [{
        "src": [10, 'branch', 'dev'],
        "srcPath": ["pipelines/service-tp.yaml"],
        "dest": [10, 'branch', 'test'],
        "destPath": ["pipelines/service-tp.yaml"]
      }],
      // projectId: '',
      // ref: 'main',
      // tree: [],
      flattenedTree: {},
      // flattenedTreeFake: {},
      // selectedPath: '',
      props: {
        expandTrigger: 'hover',
      },
      propsPath: {
        label: "path",
        value: "path",
        expandTrigger: 'hover',
      }
    };
  },
  methods: {
    addSetting() {
      this.data.push({
        "src": [],
        "srcPath": "",
        "dest": "",
        "destPath": ""
      })
    },
    removeSetting(item, index) {
      console.log("item:", item);
      if (index !== -1) {
        this.data.splice(index, 1)
      }
    },
    // 获取项目分支或 tag 的目录树
    fetchTree(projectId, ref, flg, index) {
      try {
        // console.log("请求repositorytree API前：", this.getCurrentTime());
        // const response = api.repositorytree(projectId, ref);
        api.repositorytree(projectId, ref).then(res => {
          this.flattenedTree[flg + index] = this.flattenTree(res.data);
          // loading 加载组件
          this.attr.percentage = 100 / this.data.length * (index + 1)
          if (this.data.length - 1 === index) {
            this.attr.loading = false
          }
        })
        // console.log("请求repositorytree API后：", this.getCurrentTime());

      } catch (error) {
        console.error(error);
      }
    },
    // 格式化目录树
    flattenTree(items) {

      const result = [];
      const stack = [...items];

      while (stack.length) {
        const item = stack.pop();
        result.push(item);

        if (item.type === 'tree' && item.children) {
          stack.push(...item.children.map(child => ({
            ...child,
            path: `${item.path}/${child.path}`,
          })));
        }
      }
      return result;
    },
    // async fetchTree(projectId, ref, flg, index) {
    //   // console.log("请求repositorytree API前：", this.getCurrentTime());
    //   return api.repositorytree(projectId, ref)
    //     .then(response => {
    //       // console.log("请求repositorytree API后：", this.getCurrentTime());
    //       return { data: response.data, flg, index };
    //     })
    //     .catch(error => {
    //       console.error(`Error fetching tree for projectId: ${projectId}, ref: ${ref}`, error);
    //       throw error;
    //     });
    // },
    // // 格式化目录树 异步
    // async flattenTreeAsync(items) {
    //   const result = [];
    //   const stack = [...items];

    //   while (stack.length) {
    //     const item = stack.pop();
    //     result.push(item);

    //     if (item.type === 'tree' && item.children) {
    //       const childrenWithPaths = await Promise.all(
    //         item.children.map(async (child) => ({
    //           ...child,
    //           path: `${item.path}/${child.path}`,
    //         }))
    //       );
    //       stack.push(...childrenWithPaths);
    //     }
    //   }
    //   return result;
    // },
    // async flattenTreeAsync(items) {
    //   const result = [];
    //   const stack = [...items];

    //   while (stack.length) {
    //     const item = stack.pop();
    //     result.push(item);

    //     if (item.type === 'tree' && item.children) {
    //       const childrenWithPaths = await Promise.all(
    //         item.children.map(async (child) => ({
    //           ...child,
    //           path: `${item.path}/${child.path}`,
    //         }))
    //       );
    //       stack.push(...childrenWithPaths);
    //     }
    //   }
    //   return result;
    // },
    // 获取项目列表和每个项目拥有的分支和 tag
    projectTrees() {
      api.projectTree().then(res => {
        // console.log(res.data);
        this.options = res.data
      })
    },
    // // 获取项目列表和每个项目拥有的分支和 tag
    // projectTrees() {
    //   api.projectTree().then(res => {
    //     // console.log(res.data);
    //     this.options = res.data
    //   })

    // },
    // 提交选中的文件进行比对
    fileDiff(data) {
      this.attr.diffLoading = true
      api.fileDiff(data).then(res => {
        this.diffs = res.data.data
        // this.diffsList = res.data.data
        this.attr.diffLoading = false
      })
      
    },
    handleChange(value) {
      if ([undefined, null].includes(value)) {
        console.log(`The clear value is: ${value}`);
        // ElMessage.info(`The clear value is: ${value}`)
      }
    },
    // 获取配置文件对比页面的默认数据
    getDefaultField() {
      api.defaultField().then(res => {
        if (res.data.length === 0){
          this.attr.loading = false
        }
        else if (res.data.length > 0){
          this.data = res.data;
          this.getDefaultPath(res.data);
        }
      });
      // console.log('Received default field', res);

    },
    // // 获取配置文件对比页面的默认数据
    // async getDefaultField() {
    //   console.log('Fetching default field');
    //   try {
    //     const res = await api.defaultField();
    //     console.log('Received default field', res);
    //     this.data = res.data;
    //     await this.getDefaultPath(res.data);
    //   } catch (error) {
    //     console.error('Error fetching default field', error);
    //   }
    // },
    // 获取配置文件对比页面的 srcPath 和 destPath
    getDefaultPath(data) {
      data.forEach((item, index) => {
        this.fetchTree(item.src[0], item.src[2], 'src', index)
        this.fetchTree(item.dest[0], item.dest[2], 'dest', index)
      });

    },

    // // 获取配置文件对比页面的 srcPath 和 destPath 多线程
    // async getDefaultPath2(data) {
    //   const srcRequests = data.map((item, index) => this.fetchTree(item.src[0], item.src[2], 'src', index));
    //   const destRequests = data.map((item, index) => this.fetchTree(item.dest[0], item.dest[2], 'dest', index));
    //   console.log("srcRequests:", srcRequests, "destRequests:", destRequests);

    //   try {
    //     await Promise.all([...srcRequests, ...destRequests]);
    //     console.log('Received all results');
    //   } catch (error) {
    //     console.error('Error in fetching data:', error);
    //   }
    // },
    // 当前时间
    getCurrentTime() {
      //获取当前时间并打印
      var _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
      let ms = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getMilliseconds();
      _this.gettime = yy + '/' + mm + '/' + dd + ' ' + hh + ':' + mf + ':' + ss + ':' + ms;
      return _this.gettime
    }
  },
  mounted() {
    // 获取项目列表和每个项目拥有的分支和 tag
    this.projectTrees()
    //获取配置文件对比页面的默认数据
    this.getDefaultField()
  }
};
</script>

<style scoped></style>
